package org.net5ijy.security.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;

/**
 * HibernateConfiguration
 *
 * @author XGF
 * @date 2020/11/30 22:29
 */
@Configuration
@PropertySource(value = {"classpath:application.properties"})
public class HibernateConfiguration {

  /**
   * 注入properties配置环境
   */
  @Autowired
  private Environment environment;

  /**
   * 创建SessionFactory
   */
  @Bean
  public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    // 设置数据源
    sessionFactory.setDataSource(dataSource());
    // 设置实体类所在的包
    sessionFactory.setPackagesToScan("org.net5ijy.security.bean");
    // 一些常用配置
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
  }

  private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect",
        environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.hbm2ddl.auto",
        environment.getRequiredProperty("hibernate.hbm2ddl_auto"));
    properties.put("hibernate.show_sql",
        environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql",
        environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
  }

  /**
   * 初始化数据源，使用dbcp2
   */
  @Bean
  public DataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    ds.setUrl(environment.getRequiredProperty("jdbc.url"));
    ds.setUsername(environment.getRequiredProperty("jdbc.username"));
    ds.setPassword(environment.getRequiredProperty("jdbc.password"));
    return ds;
  }

  /**
   * hibernate事务管理器，使用HibernateTransactionManager
   */
  @Bean
  @Autowired
  public HibernateTransactionManager transactionManager(
      SessionFactory sessionFactory) {
    // 使用HibernateTransactionManager
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory);
    return txManager;
  }
}
